import React, { Component } from 'react';
import { Form, Input, Switch, Button, Checkbox, InputNumber, message } from 'antd';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import { LanguageInput } from 'components/index';
import Chooser from 'components/chooser';
import Condition from 'components/condition'
import ExpirationDate from './component/expiration-date';
import ExpirationRadio from './component/expiration-radio';
import invoiceManagementService from '../invoice-management.service';

const FormItem = Form.Item;
const If = Condition.If;

class NewExpirationReminder extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isSaving: false,
      dataSources: [
        {
          key: 'enabled',
          name: messages('common.column.status')/*状态*/,
          type: 'switch',
          initialValue: false,
          required: false,
          valuePropName:'checked'
        },
        {
          key: 'sequence',
          name: messages('common.sequence')/*序号*/,
          type: 'inputNumber',
          required: true,
          params: { max: 99, min: 1, step: 1, placeholder: messages('supplier.key461')/*请填写*/, precision: 0 }
        },
        {
          key: 'description',
          name: messages('supplier.key454')/*规则说明*/,
          type: 'languageInput',
          required: true,
          params: {
            inpRule: [{ length: 30, language: 'zh_cn' }, { length: 100, language: 'en' }],
            nameChange: this.handleLanguage,
            placeholder: messages('supplier.key462')/*请填写，上限30字符*/
          }
        },
        {
          key: 'receiptTypeList',
          name: messages('common.invoice.type')/*发票类型*/,
          type: 'chooser',
          required: false,
          params: { type: 'select_invoice_type', labelKey: 'messageKey', valueKey: 'code', showNumber: true, single: false }
        },
        {
          key: 'taxCodeList',
          name: messages('supplier.key463')/*发票税收分类编码包含*/,
          type: 'chooser',
          required: false,
          params: { type: 'select_invoice_code', labelKey: 'name', valueKey: 'code', showNumber: true, single: false }
        },
        {
          key: 'expiration',
          name: messages('supplier.key464')/*过期校验*/,
          type: 'expiration',
          required: true,
          rules: { validator: this.handleSequenceValidator }
        },
        {
          key: 'effectiveTime',
          name: messages('supplier.key465')/*规则生效日期*/,
          type: 'scheduled',
          required: true,
          rules: { validator: this.handleEffectiveValidator },
          params: { className: 'particular-input-width' },
          desc:messages('supplier.key466')/*每年均按此日期计算*/
        },
        {
          key: 'expiryRemindDay',
          name: messages('supplier.key467')/*过期提醒设置*/,
          type: 'inputNumber',
          required: false,
          params: { min: 1, step: 1, className: 'particular-input-width', precision: 0 },
          before:messages('supplier.key468')/*过期前*/,
          after:messages('supplier.key469')/*天发送提醒*/
        },
        {
          key: 'forceEnabled',
          name: messages('supplier.key244')/*强管控*/,
          type: 'checkbox',
          required: false,
          after:messages('supplier.key470')/*过期后发票不可生成费用或提交报销*/,
          valuePropName: 'checked'
        }
      ],
      requestBody: { i18n: {} }
    };
  }

  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(this.props.params.recordExpiration) === JSON.stringify(nextProps.params.recordExpiration)) {
      return;
    }
    const { params: { recordExpiration } } = nextProps;
    const { form: { setFieldsValue } } = nextProps;
    let requestBody = {};
    const { sequence, enabled, description, receiptTypeList, taxCodeList, forceEnabled, staticCalibrationFlag, expiryDay,
      expiryRemindDay, effectiveTime, dynamicRuleFailureTime } = recordExpiration;
    const expiration = { staticCalibrationFlag, expiryDay, dynamicRuleFailureTime };
    Object.assign(requestBody, recordExpiration);
    this.setState({ requestBody });
    setFieldsValue({ sequence, enabled, description, receiptTypeList, taxCodeList, forceEnabled, effectiveTime, expiration, expiryRemindDay });
  }

  handleReg = (value, callback) => {
    let reg = /^(?:((0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-8])|(0[13-9]|1[0-2])-(29|30)|(0[13578]|1[02])-31))$/;
    if (!reg.exec(value)) {
      callback(messages('supplier.key471')/*请选择正确的日期*/);
    }
  };

  handleEffectiveValidator = (rule, value, callback) => {
    if (value) {
      this.handleReg(value, callback);
    }
    callback();
  };

  handleSequenceValidator = (rule, value, callback) => {
    const { staticCalibrationFlag, dynamicRuleFailureTime, expiryDay } = value;
    if (!staticCalibrationFlag) {
      this.handleReg(dynamicRuleFailureTime, callback);
    }
    if(staticCalibrationFlag && !expiryDay){
      callback(messages('common.please.enter'));
    }
    callback();
  };

  handleLanguage = (value, i18n) => {
    let { requestBody } = this.state;
    requestBody.i18n.description = i18n;
    this.setState({ requestBody });
  };

  handleSave = () => {
    let save = () => {
      const { form: { validateFieldsAndScroll } } = this.props;
      validateFieldsAndScroll((errors, values) => {
        if (!errors) {
          const { company: { companyOID } } = this.props;
          const { requestBody } = this.state;
          invoiceManagementService.submitExpirationReminder(values, requestBody, companyOID)
            .then(() => {
              message.success(messages('common.save.success', { name: '' }/*保存成功*/));
              this.props.close(true);
            })
            .finally(() => {
              this.setState({ isSaving: false });
            });
        } else {
          this.setState({ isSaving: false });
        }
      });
    };
    this.setState({ isSaving: true }, save);
  };

  handleCancel = () => {
    const { form: {resetFields} } = this.props;
    resetFields();
    this.props.close();
  };

  renderFormItem = (item) => {
    const { requestBody, requestBody: { i18n } } = this.state;
    let funObj = {
      'input': <Input {...item.params}/>,
      'switch': <Switch {...item.params}/>,
      'chooser': <Chooser {...item.params}/>,
      'checkbox': <Checkbox {...item.params}/>,
      'scheduled': <ExpirationDate {...item.params}/>,
      'expiration': <ExpirationRadio {...item.params}/>,
      'inputNumber': <InputNumber {...item.params}/>,
      'languageInput': <LanguageInput{...item.params} name={requestBody.description} isEdit={!!requestBody.id} i18nName={(i18n || {}).description}/>,
    };
    return funObj[item.type];
  };


  render() {
    const { dataSources, isSaving } = this.state;
    const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
    const { form: { getFieldValue ,getFieldDecorator} } = this.props;

    dataSources.some(item => {
      if (item.key === 'expiryRemindDay') {
        item.desc = messages('setting.key1461', { arg1: getFieldValue(item.key) || '' })/*消息内容：您的发票将于 {arg1} 过期，请尽快报销*/;
        return true;
      }
    });
    return (
      <section className="new-expiration">
        <Form onSubmit={this.handleSave}>
          {dataSources.map(item => {
            let rules = [{ required: item.required, message: messages('common.please.enter') }];
            if (item.rules) rules.push(item.rules);
            return (
              <FormItem label={item.name}  {...formItemLayout}>
                <If value={item.before}><span className="expiration-before-desc">{item.before}</span></If>
                {
                  getFieldDecorator(item.key,
                    {
                      rules: rules,
                      valuePropName: item.valuePropName || 'value'
                    }
                  )(this.renderFormItem(item))
                }
                <If value={item.after}><span>{item.after}</span></If>
                <If value={item.desc}> <span className="particular-input-desc">{item.desc}</span></If>
              </FormItem>
            );
          })}
          <div className="footer-operate">
            <Button type="primary" onClick={this.handleSave} loading={isSaving}>{messages('common.save')}</Button>
            <Button onClick={this.handleCancel} loading={isSaving}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </section>
    );
  }
}


function mapStateToProps(state) {
  return {
    company: state.login.company
  };
}

const WrappedComponent = Form.create()(NewExpirationReminder);
export default connect(mapStateToProps)(WrappedComponent);
